// !!! 登录通用函数
import { v4 } from 'uuid'
import PropTypes from 'prop-types'
import { useEventEmitter } from 'ahooks'
import { useEffect, useState } from 'react'
import { Form, Input, Button, ConfigProvider, Dropdown } from 'antd'
import { UserOutlined, LockOutlined, VideoCameraAddOutlined } from '@ant-design/icons'

import { ModelBox } from '../Model'
import { WebTemplateUrl } from '../Config/urlList'


// TODO 登录方式
// *** 帐密加扫码
export const SingleA01 = ({ toggle, active }) => {
    SingleA01.propTypes = { toggle: PropTypes.func, active: PropTypes.bool }
    return (
        <div className="switch">
            <div className={active ? 'active' : ''} onClick={() => toggle(true)}>帐号密码</div>
            <div className={active ? '' : 'active'} onClick={() => toggle(false)}>微信扫码</div>
        </div>
    )
}

// TODO 帐密登录
export const AccountSecretA01 = ({ img, config }) => {
    AccountSecretA01.propTypes = { img: PropTypes.string, config: PropTypes.object }
    // 修改密码弹出层
    const [loading, setLoading] = useState(false)
    const [UserInfo, setUserInfo] = useState()
    const [OptionsCall, setOptionsCall] = useState()
    const SignUpFunc = async (e) => {
        try {
            setLoading(true)
            setUserInfo(e)
            const { username, password } = e
            const { client_id, client_secret, grant_type } = config
            const data = { client_id, client_secret, grant_type, username, password }
            if (client_id === 'CommonManagement') setOptionsCall({ type: 'CommonLoading', title: '正在登录...', close: true, data })
            else if (client_id === 'transport') setOptionsCall({ type: 'TransportLoading', title: '正在登录...', close: true, data })
            else setOptionsCall({ type: 'SignUpLoading', title: '正在登录...', close: true, data })
        } catch (error) { setLoading(false) }
    }

    const ModalEvent = useEventEmitter()
    ModalEvent.useSubscription(val => {
        setOptionsCall()
        setLoading(false)
        if (val === 'NotPassword') setOptionsCall({ type: 'ChangePassword', title: '修改密码', close: true, data: UserInfo })
    })

    return (
        <div className="SignUp">
            <ConfigProvider theme={{ token: { colorTextPlaceholder: '#fff' } }}>
                <Form
                    className="SignUpForm"
                    layout="vertical"
                    name="basic"
                    autoComplete="off"
                    onFinish={SignUpFunc}
                >
                    <Form.Item name="username" rules={[{ required: true, message: '请输入用户账户!' }]}>
                        <Input
                            prefix={<UserOutlined className="InputIcon" />}
                            disabled={loading}
                            placeholder="请输入用户账户!"
                        />
                    </Form.Item>
                    <Form.Item name="password" rules={[{ required: true, message: '请输入用户密码!' }]}>
                        <Input.Password
                            prefix={<LockOutlined className="InputIcon" />}
                            disabled={loading}
                            placeholder="请输入用户密码!"
                        />
                    </Form.Item>
                    <Form.Item className="SignUpBtn">
                        <Button block type="primary" htmlType="submit" loading={loading}>
                            {img ? <img src={img} alt="" /> : loading ? '登录中...' : '登录'}
                        </Button>
                    </Form.Item>
                </Form>
            </ConfigProvider>
            <ModelBox OptionsCall={OptionsCall} ModalEvent={ModalEvent} />
        </div>
    )
}


// TODO 扫码登录
export const ScanCodeA01 = () => {
    const [uuid] = useState(v4())
    useEffect(() => {
        const get = 'http://47.93.180.63:8095/wechatProjects/sse'
        const codeData = {
            self_redirect: true,
            id: 'QRcode',
            appid: 'wxa3d0c46c8bfcef89',
            scope: 'snsapi_login',
            redirect_uri: window.encodeURI('https://common-redirect.ljkjkf.com'),
            state: uuid,
            style: 'white',
            href: WebTemplateUrl + 'code.css',
        }
        var eventSource = new EventSource(`${get}?QRUuid=${uuid}`)
        eventSource.onopen = () => new window.WxLogin(codeData)
        eventSource.onmessage = e => { if (e.data.includes('Bearer')) { eventSource.close() } }
        eventSource.onerror = () => eventSource.close()

        return () => { eventSource.close() }
    }, [uuid])
    return (
        <div className="CodeUpBox">
            <div id="QRcode" />
        </div>
    )
}



// TODO 额外组件下载
export const PlugInUnit = () => {
    const CMTLoad = () => window.open('https://image.ljkjkf.com/CmtClientService.exe')
    const LivePlugIn = () => window.location.href = 'https://image.ljkjkf.com/intellisiteSystem_TieKe/Common/直播插件.reg'
    const browser = () => window.open(`${window.location.origin}/VersionTips`)
    const items = [
        {
            key: '1',
            label: <div onClick={LivePlugIn}>直播插件 </div>,
            icon: <VideoCameraAddOutlined />,
        },
        {
            key: '2',
            label: <div onClick={CMTLoad}>指挥插件 </div>,
            icon: <VideoCameraAddOutlined />,
        },
        {
            key: '3',
            label: <div onClick={browser}>浏览器下载 </div>,
            icon: <VideoCameraAddOutlined />,
        },
    ]
    return (
        <Dropdown menu={{ items }} trigger={['click']}>
            <div className='PlugInUnit'> 运行项目的必要插件 </div>
        </Dropdown>
    )
}